<template>
  <AppPage
    :show-footer="true"
    bg-cover
    :style="{ backgroundImage: `url(${bgImg})` }"
  >
    <div
      style="transform: translateY(25px)"
      class="m-auto p-15 f-c-c min-w-345 max-w-700 rounded-10 card-shadow bg-white bg-opacity-60"
    >
      <template v-if="mode === 1">
        <div w-380 hidden md:block px-20 py-35>
          <img
            src="@/assets/images/login_banner.webp"
            w-full
            alt="login_banner"
          />
        </div>

        <div w-320 flex-col px-20 py-35>
          <h5 f-c-c text-24 font-normal color="#6a6a6a">
            <!-- <img class="logo-1" src="@/assets/images/logo_1.png" />
            <img class="logo-2" src="@/assets/images/logo_2.png" /> -->
            <span>{{ title }}</span>
          </h5>
          <div mt-30>
            <n-input
              v-model:value="loginInfo.name"
              autofocus
              clearable
              class="text-16 items-center h-50 pl-10"
              placeholder="请输入帐号"
              :maxlength="20"
            />
          </div>
          <div mt-30>
            <n-input
              v-model:value="loginInfo.password"
              class="text-16 items-center h-50 pl-10"
              type="password"
              clearable
              show-password-on="mousedown"
              placeholder="请输入密码"
              :maxlength="20"
              @keydown.enter="handleLogin"
            />
          </div>

          <div class="flex flex-rb flex-cc" mt-20>
            <n-checkbox
              :checked="isRemember"
              label="记住我"
              :on-update:checked="(val) => (isRemember = val)"
            />

            <n-button type="primary" quaternary @click="mode = 2">
              忘记密码？
            </n-button>
          </div>

          <div mt-20>
            <n-button
              w-full
              h-50
              rounded-5
              text-16
              type="primary"
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </n-button>
          </div>
        </div>
      </template>

      <template v-else>
        <div w-400 flex-col px-20 py-35>
          <h5 f-c-c text-24 font-normal color="#6a6a6a">重置密码</h5>
          <div mt-30>
            <n-input
              v-model:value="resetInfo.email"
              autofocus
              clearable
              class="text-16 items-center h-50 pl-10"
              placeholder="输入邮箱地址"
              :maxlength="20"
            />
          </div>
          <div class="flex flex-cc" mt-15>
            <n-input
              v-model:value="resetInfo.code"
              clearable
              class="text-16 items-center h-50 pl-10 mr-15"
              show-password-on="mousedown"
              placeholder="邮箱验证码"
              :maxlength="20"
            />
            <n-button
              type="primary"
              h-50
              :disabled="isCounting"
              :loading="loading"
              @click="sendCodeByEmail"
            >
              {{ getSmsCodeBtnText }}
            </n-button>
          </div>
          <div mt-15>
            <n-input
              v-model:value="resetInfo.newPw"
              class="text-16 items-center h-50 pl-10"
              type="password"
              clearable
              show-password-on="mousedown"
              placeholder="输入新密码"
              :maxlength="20"
              @keydown.enter="handleLogin"
            />
          </div>
          <div mt-15>
            <n-button
              w-full
              h-50
              rounded-5
              text-16
              type="primary"
              :loading="loading"
              @click="resetPassword"
            >
              重置密码
            </n-button>
          </div>
          <n-button class="mt-30" type="primary" quaternary @click="mode = 1">
            返回登录
          </n-button>
        </div>
      </template>
    </div>
  </AppPage>
</template>

<script setup>
import { ref } from 'vue'
import { lStorage, setToken, getLoginUser } from '@/utils'
import { useStorage } from '@vueuse/core'
import bgImg from '@/assets/images/login_bg.webp'
import api from './api'
import { addDynamicRoutes } from '@/router'
import { useUserStore } from '@/store'
import SM from 'sm-crypto'

const title = import.meta.env.VITE_TITLE

const router = useRouter()
const { query } = useRoute()
const userStore = useUserStore()

const loginInfo = ref({
  name: '',
  password: '',
})

const resetInfo = ref({
  email: '',
  code: '',
  newPw: '',
})

const mode = ref(1)
const timer = ref(null)
const count = ref(60)
const isCounting = ref(false)
const getSmsCodeBtnText = ref('获取验证码')

initLoginInfo()

function initLoginInfo() {
  const localLoginInfo = lStorage.get('loginInfo')
  if (localLoginInfo) {
    loginInfo.value.name = localLoginInfo.name || ''
    loginInfo.value.password = localLoginInfo.password || ''
  }
}

const isRemember = useStorage('isRemember', false)
const loading = ref(false)

async function handleLogin() {
  const { name, password } = loginInfo.value
  if (!name || !password) {
    $message.warning('请输入用户名和密码')
    return
  }
  try {
    loading.value = true
    $message.loading('正在验证...')

    const { code, data } = await api.login({
      account: name,
      password: encryptData(password.toString()),
    })

    if (code === 200) {
      $message.success('登录成功')
      setToken(data)
      await getLoginUser()
      if (isRemember.value) {
        lStorage.set('loginInfo', { name, password: password.toString() })
      } else {
        lStorage.remove('loginInfo')
      }
      await addDynamicRoutes()
      if (query.redirect) {
        const path = query.redirect
        Reflect.deleteProperty(query, 'redirect')
        router.push({ path, query })
      } else {
        router.push('/')
      }
    }
  } catch (error) {
    console.error(error)
    $message.removeMessage()
  }
  loading.value = false
}

async function sendCodeByEmail() {
  try {
    const { email } = resetInfo.value

    if (!email) {
      return $message.warning('请输入邮箱地址')
    }

    loading.value = true

    const { code } = await api.sendCodeByEmail({
      email,
    })

    loading.value = false

    if (code === 200) {
      $message.success('发送成功')
      startCounting()
    }
  } catch (err) {
    loading.value = false
  }
}

async function resetPassword() {
  try {
    const { email, code, newPw } = resetInfo.value

    if (!email) {
      return $message.warning('请输入邮箱地址')
    }

    if (!code) {
      return $message.warning('请输入邮箱验证码')
    }

    if (!newPw) {
      return $message.warning('请输入新密码')
    }

    loading.value = true

    const { code: resCode } = await api.resetPassword({
      email,
      code,
      newPw: encryptData(newPw.toString()).toUpperCase(),
    })

    loading.value = false

    if (resCode === 200) {
      $message.success('重置成功')
      mode.value = 1
      resetInfo.value = {
        email: '',
        code: '',
        newPw: '',
      }
    }
  } catch (err) {
    loading.value = false
  }
}

// 加密数据
function encryptData(data = '') {
  const sm2 = SM.sm2
  const publicKey =
    '04298364ec840088475eae92a591e01284d1abefcda348b47eb324bb521bb03b0b2a5bc393f6b71dabb8f15c99a0050818b56b23f31743b93df9cf8948f15ddb54'
  const result = sm2.doEncrypt(data, publicKey, 1)
  return result
}

function startCounting() {
  count.value = 60
  isCounting.value = true
  getSmsCodeBtnText.value = `重新获取(${count.value})`

  timer.value = setInterval(() => {
    count.value--

    if (count.value <= 0) {
      clearInterval(timer)
      isCounting.value = false
      getSmsCodeBtnText.value = '获取验证码'
    } else {
      getSmsCodeBtnText.value = `重新获取(${count.value})`
    }
  }, 1000)
}
</script>

<style lang="scss" scoped>
.logo-1 {
  height: 30px;
  margin-right: 5px;
  transform: translateY(3px);
}

.logo-2 {
  height: 25px;
}
</style>
